<?php
/**
 * Created by PhpStorm.
 * User: worry
 * Date: 2016/12/18
 * Time: 9:56
 */

namespace backend\services;


use backend\models\Category;
use common\services\BasicService;

class CategoryService extends BasicService
{
    public $id_sort;

    /**
     * 获取分类列表
     * @return array
     */
    public function getListByLevel()
    {
        $level_list = Category::find()->select('level')
            ->orderBy('level')->groupBy('level')
            ->asArray()->all();
        $list = [];
        foreach($level_list as $level){
            //逆序插入
            $list_temp = $this->getAllList(['level'=>$level['level']], 'sort DESC, cat_id DESC');
            foreach($list_temp as $val){
                $this->prepend($list, $val, $val['parent_id']);
            }
        }
        return $list;
    }


    /**
     * 前端压入分类
     * @param $list
     * @param $level
     * @param int $parent_id
     * @return mixed
     */
    public function prepend(&$list, $level, $parent_id = 0){
        $id_sort = $this->id_sort ? $this->id_sort : [];
        if($parent_id == 0){
            $this->prependToArray($level['cat_id'], $this->id_sort);
            $this->prependToArray($level, $list);
        } else {
            //查询父级ID位置
            $key = array_search($parent_id, $id_sort);
            if($key !== false){
                //插入到父级位置后面
                $this->prependToArray($level, $list, $key + 1);
            }
        }
        return $list;
    }

    /**
     * 保存数据之前的操作
     * @param $data
     * @param int $mode
     * @return array
     */
    public function beforeSave(&$data, $mode = self::CREATE, $oldData = [])
    {
        $data['parent_id'] = isset($data['parent_id']) ? $data['parent_id'] : 0;
        if($data['parent_id']) {
            $parent = $this->findModel($data['parent_id']);
            $data['level'] = $parent->level + 1;
        }
        if($data['parent_id'] == $data['cat_id']){
            return $this->returnMsg('上级分类不能是分类本身');
        } else {
            return $this->returnMsg('验证正常', true);
        }
    }


}